//
//  OpinionTrendController.m
//  Stock
//
//  Created by blacksun on 11-10-11.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "OpinionTrendController.h"

@implementation OpinionTrendController


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    loaded = YES;
    
    [loadingView removeFromSuperview];
    self.loadingView = nil;
    
    NSArray *newData = [aResult objectForKey:@"opinions"];
    
    //NSArray *temp =[newData filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"amount!=0.0"]];
    
    self.dataArray = [NSMutableArray arrayWithArray:newData];
    
    float maxTrade=0.0f,minTrade=0.0f;
    int maxAmount=0,minAmount=0;
    for (NSDictionary *dict in dataArray) {
        float trade = [[dict objectForKey:@"trade"] floatValue];
        int amount = [[dict objectForKey:@"score"] intValue];
        if (trade > maxTrade) {
            maxTrade = trade;
        }
        if (trade < minTrade || minTrade==0) {
            minTrade = trade;
        }
        if (amount > maxAmount) {
            maxAmount = amount;
        }
        if (amount < minAmount || minAmount==0) {
            minAmount = amount;
        }
        NSString *title = [dict objectForKey:@"dateId"];
        if ([title rangeOfString:@"-"].location != NSNotFound) {
            NSArray *dates = [title componentsSeparatedByString:@"-"];
            NSMutableArray *array = [NSMutableArray arrayWithArray:dates];
            if (array.count>0) {
                [array removeObjectAtIndex:0];
            }
            [xLabelTitles addObject:[array componentsJoinedByString:@"-"]];
            
        }else{
            [xLabelTitles addObject:title];
        }
    }
    
    //K线
    float margin = maxTrade-minTrade;
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(minTrade-margin) length:CPTDecimalFromFloat(2.2*margin)];
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromInteger([dataArray count])];
    
    
    
    
    //柱状图
    CPTXYPlotSpace *barSpace = (CPTXYPlotSpace *)[self.graph plotSpaceWithIdentifier:@"barSpace"];
    barSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(minAmount) length:CPTDecimalFromFloat(3*(maxAmount-minAmount))];
    barSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(1.0f) length:CPTDecimalFromInteger([dataArray count])];
    
    
    int range = [dataArray count]/5;
    //坐标
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
    axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(minTrade-margin);
    axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(range);
    axisSet.xAxis.minorTicksPerInterval = 0;
    NSMutableArray *labels = [NSMutableArray array];
    int labelsCount = [dataArray count]/range;
    //NSLog(@"count=%d,labels=%d",[dataArray count],labelsCount);
    for (int i=0; i<labelsCount+1; i++) {
        NSString *title = @"";
        NSLog(@"range=%d,count-1=%d",i*range,[xLabelTitles count]-1);
        if ([xLabelTitles count]>0 && i*range<=[xLabelTitles count]-1) {
            title = [xLabelTitles objectAtIndex:i*range];
        }
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:title textStyle:axisSet.xAxis.labelTextStyle];
        NSNumber *tickLocation = [NSDecimalNumber numberWithInt:i*range];
		newLabel.tickLocation = [tickLocation decimalValue];
		[labels addObject:newLabel];
		[newLabel release];
    }
	axisSet.xAxis.axisLabels =  [NSSet setWithArray:labels];
    //NSLog(@"%f,%f",maxTrade,minTrade);
    float labelRange = 0.1;
    if (maxTrade-minTrade > 0.4) {
        labelRange = (maxTrade-minTrade)/3;
    }
    axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(labelRange);
    axisSet.yAxis.minorTicksPerInterval = 0;
    axisSet.yAxis.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0.00");
    /*NSMutableArray *yLabels = [NSMutableArray array];
     for (int i=0; i<4; i++) {
     CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:@"10.01" textStyle:axisSet.xAxis.labelTextStyle];
     NSNumber *tickLocation = [NSDecimalNumber numberWithInt:i*2];
     newLabel.tickLocation = [tickLocation decimalValue];
     [labels addObject:newLabel];
     [newLabel release];
     }
     axisSet.yAxis.axisLabels = [NSSet setWithArray:yLabels];
     */
	NSArray *exclusionRanges  = [NSArray arrayWithObjects:
								 [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(minTrade)],
								 nil];
	axisSet.yAxis.labelExclusionRanges = exclusionRanges;
    
    CPTScatterPlot *dataSourceLinePlot = (CPTScatterPlot *)[graph plotWithIdentifier:@"kPlot"];
    
    CPTColor *beginColor = [CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:0.8];
    CPTColor *endColor = [CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:0.3];
    CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor:beginColor endingColor:endColor];
    areaGradient.angle = -90.0f;
	CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient];
    dataSourceLinePlot.areaFill = areaGradientFill;
    dataSourceLinePlot.areaBaseValue = CPTDecimalFromDouble(minTrade-margin);
    
    
    [self.graph reloadData];
}


#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self performSelector:@selector(loadChartData) withObject:nil afterDelay:0.1];
}


-(void)loadChartData{
    NSString *uri = [NSString stringWithFormat:@"opinion/trend?id=%@",stockId];
    [service queryChartDataWithUri:uri];
}


-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index 
{
    NSDictionary *dataCell = [dataArray objectAtIndex:index];
    NSDecimalNumber *num = nil;
    if ([plot.identifier isEqual:@"kPlot"]) {
        switch ( fieldEnum ) {
            case CPTScatterPlotFieldX:
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
                break;
            case CPTScatterPlotFieldY:{
                if ([dataCell isEqual:[NSNull null]]) {
                    num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:0.0f];
                }else{
                    float value = [[dataCell objectForKey:@"trade"] floatValue];
                    num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:value];
                }
                //NSLog(@"%f",[num floatValue]);
            }
                break;
        }
    }else{
        if (fieldEnum == CPTBarPlotFieldBarLocation) {
            num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index];
        }else if (fieldEnum == CPTBarPlotFieldBarTip ) {
            if ([dataCell isEqual:[NSNull null]]) {
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:0.0f];
            }else{
                float value = [[dataCell objectForKey:@"score"] floatValue];
                num = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:value];
            }
        }
        
    }
    return num;
}

@end
